/*
 * @Description: 线路收藏列表模块.如果该模块放入路由中，则需hasRouter设置为true，会在activated刷新收藏列表
 * @Author: yingying.fan
 * @Date: 2019-07-01 12:54:05
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-07-01 13:02:38
 */
<template>
  <div class="fontsize24 collection-list-wrapper">
    <template v-if="list.length>0">
      <collection
        v-for="(item,index) in list"
        :key="`collection_${index}`"
        :index="index"
        :lineInfo="item"
        @removeCollection="removeCollection"
      ></collection>
    </template>
    <no-collection v-else>
    </no-collection>
  </div>
</template>

<script>
import { getColletctedList } from './api.js'
import { setRouteCollected } from '../nearbysite/CollectionUtils'
import CollectionItem from './CollectionItem'
import NoCollection from './NoCollection'
export default {
  components: {
    'collection': CollectionItem,
    'no-collection': NoCollection
  },
  props: {
    // 该组件是否被包裹在路由中，需要启用activated和deactivated生命周期
    hasRouter: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isActive: false, // 当前组件是否被激活
      list: []
    }
  },
  mounted() {
    document.addEventListener(
      'resume',
      () => {
        // 有数据时收到resume事件，刷新一下收藏数据
        if (this.isActive) {
          this.getList()
        }
      },
      false
    )

    if (!this.hasRouter) {
      this.getList()
    }
  },
  activated() {
    this.isActive = true
    this.getList()
  },
  deactivated() {
    this.isActive = false
  },
  methods: {
    getList() {
      console.log('~~~获取收藏列表~~~')
      getColletctedList().then(res => {
        if (JSON.stringify(res) !== JSON.stringify(this.list)) {
          this.list = res
        }
      })
    },
    removeCollection(index, lineInfo) {
      let {
        routeId,
        direction,
        routeName,
        startStation,
        endStation,
        startTime,
        endTime,
        price,
        isCollected
      } = lineInfo
      setRouteCollected(
        isCollected,
        routeId,
        direction,
        routeName,
        startStation,
        endStation,
        startTime,
        endTime,
        price
      ).then(isCollected => {
        console.log('~~~取消收藏~~~', isCollected)
        // 取消收藏埋点埋点
        this.$ThirdParty.then(thirdparty => {
          thirdparty.doRecordEvent(
            'bus_line_unfav',
            JSON.stringify({ LINE: this.routeId }),
            1,
            function () { },
            function (err) {
              console.log(err)
            }
          )
        })
        this.$Toast.then(Toast => {
          Toast.showShortBottom('取消收藏')
        })
        this.$delete(this.list, index)
      })
    }
  }
}
</script>

<style scoped>
.collection-list-wrapper {
  color: #333333;
  margin-bottom: 36px;
}
</style>
